/*
 * @(#)DocumentInvitationManager.java 
 * Copyright (c) 2006 DCIVision Ltd All rights reserved.
 * 
 *  This software is the confidential and proprietary information of DCIVision Ltd 
 *  ("Confidential Information"). You * shall not disclose such Confidential
 *   Information and shall use it only in accordance with the terms of the 
 *   license agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.alert.core;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;

import com.dcivision.alert.InvitationFacade;
import com.dcivision.alert.bean.MtmUpdateAlertRecipient;
import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertLogAction;
import com.dcivision.alert.bean.UpdateAlertSystemLog;
import com.dcivision.alert.bean.UpdateAlertType;
import com.dcivision.alert.dao.MtmUpdateAlertRecipientDAObject;
import com.dcivision.alert.dao.UpdateAlertDAObject;
import com.dcivision.alert.dao.UpdateAlertLogActionDAObject;
import com.dcivision.alert.dao.UpdateAlertSystemLogDAObject;
import com.dcivision.alert.dao.UpdateAlertTypeDAObject;
import com.dcivision.alert.web.MaintUpdateAlertForm;
import com.dcivision.audit.AuditTrailConstant;
import com.dcivision.audit.core.AuditTrailManager;
import com.dcivision.dms.EmailAuditTrailConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsEmailAuditTrail;
import com.dcivision.dms.bean.DmsSendEmail;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.dao.DmsEmailAuditTrailDAObject;
import com.dcivision.dms.web.MaintDmsInvitationForm;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ApplicationExceptionList;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SchedulerFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.dao.InviteePickerHistoryDAObject;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.bean.UserRole;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.user.dao.UserRoleDAObject;

/**
 * <p>
 * Class Name: DocumentInvitationManager
 * </p>
 * 
 * @author Greatwall Shao
 * @company DCIVision Limited
 * @creation date 2006-11-27
 */
public class DocumentInvitationManager {

  private static final int DOCUMENT_INVITATION_PAGE_OFFSET = 10;

  private static final String STATUS_EXPIRED = "E";

  public static final String STATUS_ACTIVE  = "A";

  private SessionContainer    sessionContainer;

  private Connection          dbConn;

  protected Log               logger         = LogFactory.getLog(this.getClass().getName());

  public DocumentInvitationManager(SessionContainer sessionContainer, Connection dbCon) {
    
    this.sessionContainer = sessionContainer;
    try{
      dbConn=DataSourceFactory.getConnection();
    }catch(Exception e){
      this.dbConn = dbCon;
    }
  }

  public void createInvitation(MaintDmsInvitationForm form) throws ApplicationException,
      SchedulerException {
    
    MaintDmsInvitationForm maintUpdateAlertForm = form;
    
    InviteePickerHistoryDAObject inviteePickerHistoryDAObject = new InviteePickerHistoryDAObject(sessionContainer,dbConn);

    String externalInviteeStr = maintUpdateAlertForm.getExternalInvitee();
    if(Utility.isEmpty(externalInviteeStr)||externalInviteeStr.trim().equalsIgnoreCase("null")){
      externalInviteeStr="";
    }
    String documentID = maintUpdateAlertForm.getDocID();
    String message = maintUpdateAlertForm.getMessage();
    String subject = maintUpdateAlertForm.getSubject();
    String notifyWay = maintUpdateAlertForm.getNotifyWay();
    
    if (Utility.isEmpty(notifyWay)) {
      notifyWay = new String(UpdateAlert.EMAIL_NOTIFICATION+UpdateAlert.SYSTEM_NOTIFICATION);
    }
    
    
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer,
        dbConn);
    DmsDocument document = docRetrievalManager.getDocument(TextUtility
        .parseIntegerObj(documentID));
    
    String locationPath = docRetrievalManager.getLocationPath(document.getParentID()) + "\\"
                                                                      + document.getDocumentName();
    String objectName = document.getDocumentName();
    /**
    if(Utility.isEmpty(subject)){
      subject = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), 
          "home.message.document_invitation.read",objectName);
    }*/
    
    // insert record into UPDATE_ALERT
    UpdateAlert updateAlert = new UpdateAlert();
    updateAlert.setObjectID(TextUtility.parseIntegerObj(documentID));
    updateAlert.setObjectType(GlobalConstant.OBJECT_TYPE_DOCUMENT);
    
    updateAlert = creatUpdateAlert(updateAlert);
    
    logger.debug(updateAlert.getID());
    
    updateAlert.setMessage(message);
    updateAlert.setAlertSubject(subject);
    updateAlert.setDueDate(maintUpdateAlertForm.parseTimestamp(maintUpdateAlertForm.getDueDate()));
    
    UpdateAlertType updateAlertType = getUpdateAlertTypeByNotifyWay(updateAlert, UpdateAlert.INVITE_TYPE, notifyWay);
    
    AlertManager alertManager = new AlertManager(sessionContainer, dbConn);

    String[] allUserList = maintUpdateAlertForm.getUserList();
    String[] allGroupList = maintUpdateAlertForm.getGroupList();
    String[] allRoleList = maintUpdateAlertForm.getRoleList();
    String[] allExternalEmailList =TextUtility.splitString(externalInviteeStr,";");
    
    inviteePickerHistoryDAObject.updateInviteeHistory(allUserList, allGroupList, allRoleList, SystemFunctionConstant.DMS);

    MtmUpdateAlertRecipient[] updateRecipient;
    updateRecipient = alertManager.getRecipient(allUserList,
        allGroupList, allRoleList, allExternalEmailList, null, null);

    List notifyUserIDList = alertManager.getDistinctUserIDListByLists(allUserList, allGroupList,
        allRoleList);
      
    createInviteTypesRecipientsNLogs(updateAlert, updateAlertType, updateRecipient, objectName,
        objectName, sessionContainer.getUserRecordID(), notifyUserIDList, null, null);
  
    StringBuffer toAddress = getToEmailAddress(notifyUserIDList, externalInviteeStr);
    logger.debug(toAddress);    
    if (!Utility.isEmpty(toAddress)) {
      addEmailAuditTrail(subject, toAddress, locationPath);
    }

    
//  audit trail add by barbin for document audit trail 2006-12-06
    if (sessionContainer.getUserRecordID() != null) {
        AuditTrailManager auditManager = new AuditTrailManager(sessionContainer, dbConn);
        auditManager.auditTrail(GlobalConstant.OBJECT_TYPE_DOCUMENT, document, AuditTrailConstant.ACCESS_TYPE_INVITATION_CREATE, document.getVersionNumber());
        auditManager.release();
      }

    // add view alert
    //addViewAlert(maintUpdateAlertForm, updateAlert, alertManager, docOperationManager);
    if (!Utility.isEmpty(externalInviteeStr)&&!externalInviteeStr.trim().equalsIgnoreCase("null")) {
      try {
        sendExternalEmail(externalInviteeStr, subject, message, documentID);
      }
      catch (Exception e) {
        logger.error("email send error :"+e.toString());
      }
    }
    this.release();
  }

  /**
   * 
   */
  private void release() {
    try {
      dbConn.commit();
    }
    catch (SQLException e) {
      logger.error(e, e);
    }
    try {
      dbConn.close();
    }
    catch (SQLException e) {
      logger.error(e, e);
    }
    finally{
      dbConn=null;
    }
  }

  /**
   * @param notifyUserIDList
   * @param externalInviteeStr
   * @return 
   */
  private StringBuffer getToEmailAddress(List notifyUserIDList, String externalInviteeStr) {
    StringBuffer toAddress = new StringBuffer();
    for (int i = 0; i < notifyUserIDList.size(); i++) {
      // Disable the notification to creatror
      Integer userID = (Integer) notifyUserIDList.get(i);
      String userEmail = UserInfoFactory.getUserEmailAddress(userID);
      if (!Utility.isEmpty(userEmail)) {
        toAddress.append(userEmail + " ; ");
      }
    }
    
      if(!Utility.isEmpty(externalInviteeStr)&&!externalInviteeStr.trim().equalsIgnoreCase("null")){
        toAddress.append(externalInviteeStr);
      }
      return toAddress;
  }
/**
 * 
 * @param maintDmsUpdateAlertForm
 * @throws ApplicationException
 */
  private void sendExternalEmail(String extraRecipients,String subject,String message,String documentID)
      throws ApplicationException {
    boolean support_email = SystemParameterFactory
        .getSystemParameterBoolean(SystemParameterConstant.SUPPORT_EMAIL);
    if (support_email) {
      sendInvitationEmail(extraRecipients,subject,message,documentID);
    }
  }

  /**
   * @param form
   * @return
   * @throws ApplicationException
   */
  private void sendInvitationEmail(String extraRecipients,String subject,String message,String documentID) 
                    throws ApplicationException {
   
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer,
        dbConn);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer,
        dbConn);

    DmsDocument document = docRetrievalManager.getDocument(TextUtility
        .parseIntegerObj(documentID));

    // Check for enternal parties invitation using email
    if (!Utility.isEmpty(extraRecipients)&&!extraRecipients.trim().equalsIgnoreCase("null")) {
      String[] externalEmails = TextUtility.splitString(extraRecipients, ";");
      for (int i = 0; i < externalEmails.length; i++) {
        DmsSendEmail email = new DmsSendEmail();
        email.setSender(UserInfoFactory.getUserEmailAddress(sessionContainer.getUserRecordID()));
        email.setRecipients(externalEmails[i]);
        if (!Utility.isEmpty(subject)) {
          email.setSubject(subject);
        }
        if (!Utility.isEmpty(message)) {
          email.setContent(message);
        }
        docOperationManager.sendDocumentByEmailAttachement(email.getSender(), email, document, null);
      }
    }
    docRetrievalManager.release();
    docOperationManager.release();

  }

  /**
   * @param updateAlert
   * @return
   * @throws ApplicationException
   */
  private UpdateAlert creatUpdateAlert(UpdateAlert updateAlert) throws ApplicationException {
    UpdateAlert newupdateAlert = new UpdateAlert();
    try {
      UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer, dbConn);

      newupdateAlert = (UpdateAlert) updateAlertDAO.getByUserID(updateAlert.getObjectType(),
          sessionContainer.getUserRecordID(), updateAlert.getObjectID());
      if (newupdateAlert == null) {
        newupdateAlert = (UpdateAlert) updateAlertDAO.insertObject(updateAlert);
      }
    }
    catch (ApplicationException appEx) {
      logger.error(appEx.toString());
      throw appEx;
    }
    catch (Exception e) {
      logger.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }
    return newupdateAlert;
  }

  /**
   * @param updateAlert
   * @param updateType
   * @param updateRecipient
   * @param objectName
   * @param eventName
   * @param creatorID
   * @param notifyUserIDList
   * @param externalEmailList 
   * @param refObjID 
   * @throws ApplicationException
   */
  private void createInviteTypesRecipientsNLogs(UpdateAlert updateAlert,
      UpdateAlertType updateType, MtmUpdateAlertRecipient[] updateRecipient, String objectName,
      String eventName, Integer creatorID, List notifyUserIDList, List externalEmailList,
      String refObjID) throws ApplicationException {
    NotificationAdapter na = new NotificationAdapter(sessionContainer, dbConn);
    UpdateAlertTypeDAObject updateTypeDAO = new UpdateAlertTypeDAObject(sessionContainer, dbConn);
    MtmUpdateAlertRecipientDAObject alertRecipientDAO = new MtmUpdateAlertRecipientDAObject(
        sessionContainer, dbConn);
    UpdateAlertSystemLogDAObject alertSystemDAO = new UpdateAlertSystemLogDAObject(
        sessionContainer, dbConn);
    ApplicationExceptionList exceptionList = new ApplicationExceptionList();
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer,
        dbConn);
    try {
      UpdateAlertType updateAlertType = updateType;
      updateAlertType.setUpdateAlertID(updateAlert.getID());
      updateAlertType = (UpdateAlertType) updateTypeDAO.insertObject(updateAlertType);
      if (UpdateAlert.DOCUMENT_TYPE.equals(updateAlert.getObjectType())
          && UpdateAlert.INVITE_ACTION.equals(updateAlertType.getActionType())) {
        try {
          addDocumentInvitationExpiredJob(updateAlertType.getDueDate(), updateAlertType.getID()
              .toString());
        }
        catch (Exception e) {
          logger.error(e, e);
        }        
      }
      for (int r = 0; r < updateRecipient.length; r++) {
        MtmUpdateAlertRecipient recipient = updateRecipient[r];
        recipient.setUpdateAlertID(updateAlert.getID());
        recipient.setUpdateAlertTypeID(updateAlertType.getID());
        alertRecipientDAO.insertObject(recipient);
      }
      
      // Active the Email Alert
      try {
        if (updateAlertType.getNotifyWay().indexOf(UpdateAlert.EMAIL_NOTIFICATION)>=0) {
          na.notifyByEmailInvite(updateAlert,updateAlertType, updateRecipient,objectName, null,eventName, 
            notifyUserIDList, externalEmailList, null,refObjID);
        }
      }
      catch (ApplicationException appEx) { // in case cannot send email and exception is thrown
        logger.info("Cannot send invitation email.");
        logger.error(appEx.toString());
        exceptionList.addException(appEx);
      }

      // Active the System Log
      if (updateAlertType.getNotifyWay().indexOf(UpdateAlert.SYSTEM_NOTIFICATION)>=0) {
        UpdateAlertSystemLog alertSystemLog = new UpdateAlertSystemLog();
        alertSystemLog.setActionUserID(sessionContainer.getUserRecordID());
        alertSystemLog.setUpdateAlertTypeID(updateAlertType.getID());
        alertSystemLog.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
        if (UpdateAlert.DOCUMENT_INVITATION_EXPIRED.equals(updateAlertType.getActionType())
            || UpdateAlert.DOCUMENT_INVITATION_CANCEL.equals(updateAlertType.getActionType())
            || UpdateAlert.DOCUMENT_INVITATION_UPDATE_DUEDATE.equals(updateAlertType.getActionType())) {
          alertSystemLog.setRefObjectID(TextUtility.parseIntegerObj(refObjID));
        }
        alertSystemLog = (UpdateAlertSystemLog) alertSystemDAO.insertObject(alertSystemLog);
      }
      
      docOperationManager.setAlertInviteID(updateAlert.getObjectID(), updateAlertType.getID());
      
      dbConn.commit();
      updateTypeDAO = null;
      alertRecipientDAO = null;
      alertSystemDAO = null;
      na.release();
    }
    catch (ApplicationException appEx) {
      logger.error(appEx, appEx);
    }
    catch (Exception e) {
      logger.error(e, e);
    } finally {
      docOperationManager.release();
    }
  }

  /**
   * @param dueDate 
   * @param updateAlertTypeID 
   * @throws SchedulerException
   */
  private void addDocumentInvitationExpiredJob(Date dueDate, String updateAlertTypeID)
      throws SchedulerException {
    if (!Utility.isEmpty(dueDate)) {
      
      Date newduedate = addTime(dueDate, Calendar.DAY_OF_MONTH, 1);
      
      if (newduedate.after(new Date())) {
        logger.info("add document invitation expiry job" + newduedate.toString());
        logger.info("job name" + GlobalConstant.DOCUMENT_INVITATION_JOB_NAME + updateAlertTypeID);

        Date startTime = newduedate;
        Scheduler sched = null;
        SimpleTrigger trigger = null;
        sched = SchedulerFactory.getScheduler();
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("updateAlertTypeID", updateAlertTypeID);
        JobDetail job = new JobDetail(GlobalConstant.DOCUMENT_INVITATION_JOB_NAME
            + updateAlertTypeID, GlobalConstant.DOCUMENT_INVITATION_JOB_GROUP,
            DocumentInvitationExpiredJob.class);
        job.setJobDataMap(dataMap);
        trigger = new SimpleTrigger(
            GlobalConstant.DOCUMENT_INVITATION_JOB_NAME + updateAlertTypeID,
            GlobalConstant.DOCUMENT_INVITATION_JOB_GROUP, startTime);
        trigger.setJobGroup(GlobalConstant.DOCUMENT_INVITATION_JOB_GROUP);
        trigger.setJobName(GlobalConstant.DOCUMENT_INVITATION_JOB_NAME + updateAlertTypeID);
        sched.scheduleJob(job, trigger);
      }
    }
  }

  /**
   * @param dueDate
   * @param type TODO
   * @param len TODO
   * @return
   */
  private Date addTime(Date dueDate, int type, int len) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(dueDate);
    cal.add(type, len);
    Date newduedate = cal.getTime();
    return newduedate;
  }

  /**
   * @param maintUpdateAlertForm
   * @param toAddress
   * @param locationPath
   * @param updateAlert
   * @param alertManager
   * @param docOperationManager
   * @throws ApplicationException
   */
  private void addViewAlert(MaintUpdateAlertForm maintUpdateAlertForm, UpdateAlert updateAlert,
      AlertManager alertManager, DocumentOperationManager docOperationManager)
      throws ApplicationException {
    MtmUpdateAlertRecipient[] updateRecipient = new MtmUpdateAlertRecipient[1];
    MtmUpdateAlertRecipient mtmUpdateAlertRecipient = new MtmUpdateAlertRecipient();
    mtmUpdateAlertRecipient.setRecipientType(GlobalConstant.SUBJECT_TYPE_USER);
    mtmUpdateAlertRecipient.setRecipientID(sessionContainer.getUserRecordID());
    updateRecipient[0] = mtmUpdateAlertRecipient;
    UpdateAlertType[] updateAlertTypes = new UpdateAlertType[1];
    updateAlertTypes[0] = getUpdateAlertType(updateAlert, UpdateAlert.VIEW_ACTION);
    updateAlert = alertManager.createUpdateAlert(updateAlert, updateAlertTypes, null,
        updateRecipient);
    docOperationManager.setAlertEditID(TextUtility.parseIntegerObj(maintUpdateAlertForm
        .getObjectID()), TextUtility.parseIntegerObj(maintUpdateAlertForm.getID()));

  }

  /**
   * @param updateAlert
   * @param actionType
   * @return
   */
  private UpdateAlertType getUpdateAlertType(UpdateAlert updateAlert, String actionType) {

    UpdateAlertType updateAlertType = new UpdateAlertType();
    updateAlertType.setUpdateAlertID(updateAlert.getID());
    updateAlertType.setActionType(actionType);
    updateAlertType.setNotifyWay(UpdateAlert.EMAIL_NOTIFICATION + UpdateAlert.SEPARATOR
        + UpdateAlert.SYSTEM_NOTIFICATION);
    updateAlertType.setMessage(updateAlert.getMessage());
    updateAlertType.setAlertSubject(updateAlert.getAlertSubject());
    updateAlertType.setDueDate(updateAlert.getDueDate());
    return updateAlertType;
  }
  
  /**
   * @param updateAlert
   * @param actionType
   * @param notifyWay
   * @return
   */
  private UpdateAlertType getUpdateAlertTypeByNotifyWay(UpdateAlert updateAlert, String actionType, String notifyWay) {

    UpdateAlertType updateAlertType = new UpdateAlertType();
    updateAlertType.setUpdateAlertID(updateAlert.getID());
    updateAlertType.setActionType(actionType);
    updateAlertType.setNotifyWay(notifyWay);
    updateAlertType.setMessage(updateAlert.getMessage());
    updateAlertType.setAlertSubject(updateAlert.getAlertSubject());
    updateAlertType.setDueDate(updateAlert.getDueDate());
    return updateAlertType;
  }

  /**
   * @param maintUpdateAlertForm
   * @param toAddress
   * @param locationPath
   */
  private void addEmailAuditTrail(String subject,StringBuffer toAddress, String locationPath) {
    try {
      // add Email Audit Trail Record;
      DmsEmailAuditTrail dmsEmailAuditTrail = new DmsEmailAuditTrail();
      DmsEmailAuditTrailDAObject emailDAO = new DmsEmailAuditTrailDAObject(sessionContainer, dbConn);
      dmsEmailAuditTrail.setUserid(sessionContainer.getUserRecordID());
      dmsEmailAuditTrail
          .setOperation(EmailAuditTrailConstant.OPERATION_EXTERNAL_DOCUMENT_INVITATION);
      dmsEmailAuditTrail.setEmailType(EmailAuditTrailConstant.EMAIL_TYPE_OUTBOUND);
      dmsEmailAuditTrail.setEmailFrom(UserInfoFactory.getUserEmailAddress(
          sessionContainer.getUserRecordID()).toString());
      String recipients = "";//maintUpdateAlertForm.getRecipients();
      if (!Utility.isEmpty(toAddress)) {
        if (!Utility.isEmpty(recipients)) {
          dmsEmailAuditTrail.setEmailTo(recipients.replaceAll(",", ";") + ";"
              + toAddress.toString().replaceAll(",", ";"));
        }
        else {
          dmsEmailAuditTrail.setEmailTo(toAddress.toString().replaceAll(",", ";"));
        }

      }
      else {
        dmsEmailAuditTrail.setEmailTo(recipients.replaceAll(",", ";"));
      }
      // dmsEmailAuditTrail.setEmailCc(maintUpdateAlertForm.getCCRecipients().replaceAll(",",";"));
      // dmsEmailAuditTrail.setEmailBcc(maintUpdateAlertForm.getBCCRecipients().replaceAll(",",";"));
      dmsEmailAuditTrail.setEmailSubject(subject);
      dmsEmailAuditTrail.setAttchSource("DMS");
      dmsEmailAuditTrail.setAttchName(locationPath);
      dmsEmailAuditTrail.setSentDate(Utility.getCurrentTimestamp().toString());
      dmsEmailAuditTrail.setAttchCount(new Integer(1));
      dmsEmailAuditTrail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
      dmsEmailAuditTrail.setCreatorID(sessionContainer.getUserRecordID());
      dmsEmailAuditTrail.setCreateDate(Utility.getCurrentTimestamp());
      dmsEmailAuditTrail.setUpdateCount(new Integer(0));
      dmsEmailAuditTrail.setUpdaterID(sessionContainer.getUserRecordID());
      dmsEmailAuditTrail.setUpdateDate(Utility.getCurrentTimestamp());
      dmsEmailAuditTrail = (DmsEmailAuditTrail) emailDAO.insertObject(dmsEmailAuditTrail);

    }
    catch (Exception e) {
      logger.error(e, e);
    }
  }
/**
 * 
 * @param updateAlertTypeID
 * @param duedate
 * @throws ApplicationException
 * @throws SchedulerException
 */
  public void updateDueDate(Integer updateAlertTypeID, String duedate) throws ApplicationException,
      SchedulerException {
    UpdateAlertTypeDAObject updateAlertTypeDAObject = new UpdateAlertTypeDAObject(sessionContainer,
        dbConn);
    updateAlertTypeDAObject.updateDueDateByID(updateAlertTypeID, duedate);
    updateExpiredJob(updateAlertTypeID, duedate);
    notificationInviteeInviteChange(updateAlertTypeID.toString(), UpdateAlert.DOCUMENT_INVITATION_UPDATE_DUEDATE);
  }

  /**
   * @param updateAlertTypeID
   * @param duedate
   * @throws SchedulerException
   */
  private void updateExpiredJob(Integer updateAlertTypeID, String duedate)
      throws SchedulerException {
    if (!Utility.isEmpty(duedate)) {
      rescheduleExpiredJob(updateAlertTypeID, duedate);
    }
    else {
      deleteExpiredJob(updateAlertTypeID);
    }
  }

  /**
   * @param updateAlertTypeID
   * @param duedate
   * @throws SchedulerException
   */
  private void rescheduleExpiredJob(Integer updateAlertTypeID, String duedate)
      throws SchedulerException {
    Date startTime = null;
    try {
      startTime = TextUtility.getDBDateTimeFormat().parse(duedate);
    }
    catch (java.text.ParseException e1) {
      try {
        startTime = TextUtility.getDateFormat().parse(duedate);
      }
      catch (ParseException e) {
        startTime = null;
      }
    }
//    Scheduler sched = null;
//    SimpleTrigger trigger = null;
//    sched = SchedulerFactory.getScheduler();
//    trigger = new SimpleTrigger(DocumentInvitationExpiredJob.JOB_NAME
//        + String.valueOf(updateAlertTypeID), DocumentInvitationExpiredJob.JOB_GROUP, startTime);
//    trigger.setJobName(DocumentInvitationExpiredJob.JOB_NAME + String.valueOf(updateAlertTypeID));
//    trigger.setJobGroup(DocumentInvitationExpiredJob.JOB_GROUP);
//    sched.rescheduleJob(DocumentInvitationExpiredJob.JOB_NAME + String.valueOf(updateAlertTypeID),
//        DocumentInvitationExpiredJob.JOB_GROUP, trigger);
    try {
      deleteExpiredJob(updateAlertTypeID);
      addDocumentInvitationExpiredJob(startTime, updateAlertTypeID.toString());
    }
    catch (SchedulerException e) {
     logger.error(e,e);
    }
  }
/**
 * 
 * @param updateAlertTypeID
 * @throws ApplicationException
 */
  public void handleInvitationExpired(String updateAlertTypeID) throws ApplicationException {
    notificationInviteeInviteChange(updateAlertTypeID, UpdateAlert.DOCUMENT_INVITATION_EXPIRED);
  }

  /**
   * @param updateAlertTypeID
   * @param changeType
   * @throws ApplicationException
   */
  private void notificationInviteeInviteChange(String updateAlertTypeID, String changeType)
      throws ApplicationException {
    UpdateAlertTypeDAObject updateAlertTypeDAObject = new UpdateAlertTypeDAObject(sessionContainer,
        dbConn);
    UpdateAlertDAObject updateAlertDAObject = new UpdateAlertDAObject(sessionContainer, dbConn);
    UpdateAlertType updateAlertType = (UpdateAlertType) updateAlertTypeDAObject
        .getByupdateAlertTypeID(TextUtility.parseIntegerObj(updateAlertTypeID));
    UpdateAlert updateAlert = (UpdateAlert) updateAlertDAObject.getObjectByID(updateAlertType
        .getUpdateAlertID());
    updateAlert.setDueDate(updateAlertType.getDueDate());
    if(Utility.isEmpty(sessionContainer.getUserRecord())
        || Utility.isEmpty(sessionContainer.getUserRecordID())) {
      UserRecord userRecord = new UserRecord();
      userRecord.setID(updateAlertType.getCreatorID());
      sessionContainer.setUserRecord(userRecord);
    }
    UpdateAlertType newUpdateAlertType = getUpdateAlertType(updateAlert, changeType);
    
    String docName = getObjectName(updateAlert);
    
    AlertManager alertManager = new AlertManager(sessionContainer, dbConn);
    MtmUpdateAlertRecipientDAObject mtmUpdateAlertRecipientDAObject = new MtmUpdateAlertRecipientDAObject(
        sessionContainer, dbConn);
    List userList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(updateAlert.getID(),
        updateAlertType.getID(), UpdateAlert.USER_RECIPIENT, GlobalConstant.RECORD_STATUS_ACTIVE);
    List groupList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(updateAlert.getID(),
        updateAlertType.getID(), UpdateAlert.GROUP_RECIPIENT, GlobalConstant.RECORD_STATUS_ACTIVE);
    List roleList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(updateAlert.getID(),
        updateAlertType.getID(), UpdateAlert.ROLE_RECIPIENT, GlobalConstant.RECORD_STATUS_ACTIVE);
    List externalEmailList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(
        updateAlert.getID(), updateAlertType.getID(), UpdateAlert.EXTERNAL_EMAIL,
        GlobalConstant.RECORD_STATUS_ACTIVE);

    String[] allUserList = new String[userList.size()];
    String[] allGroupList =  new String[groupList.size()];
    String[] allRoleList =  new String[roleList.size()]; 
    String[] allExternalEmailList =  new String[externalEmailList.size()]; 
    
    for(int i=0;i<userList.size();i++){
      if(!Utility.isEmpty(userList.get(i))){
        allUserList[i] = userList.get(i).toString();
      }
    }
    for(int i=0;i<groupList.size();i++){
      if(!Utility.isEmpty(groupList.get(i))){
        allGroupList[i] = groupList.get(i).toString();
      }
    } 
    for(int i=0;i<roleList.size();i++){
      if(!Utility.isEmpty(roleList.get(i))){
        allRoleList[i] = roleList.get(i).toString();
      }
    } 
    for(int i=0;i<externalEmailList.size();i++){
      if(!Utility.isEmpty(externalEmailList.get(i))){
        allExternalEmailList[i] = externalEmailList.get(i).toString();
      }
    }
    MtmUpdateAlertRecipient[] updateRecipient;
    updateRecipient = alertManager.getRecipient(allUserList,
        allGroupList, allRoleList, allExternalEmailList, null, null);

    List notifyUserIDList = alertManager.getDistinctUserIDListByLists(allUserList, allGroupList,
        allRoleList);

    externalEmailList = alertManager.getExternalEmailByRecipientIDList(externalEmailList);

    createInviteTypesRecipientsNLogs(updateAlert, newUpdateAlertType, updateRecipient, docName, docName,
        sessionContainer.getUserRecordID(), notifyUserIDList, externalEmailList, updateAlertType
            .getID().toString());

    this.release();
  }

  /**
   * @param updateAlert
   * @return
   * @throws ApplicationException
   */
  private String getObjectName(UpdateAlert updateAlert) throws ApplicationException {
    DmsDocument dmsDocument = new DmsDocument();

    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer,
        dbConn);
      dmsDocument = docRetrievalManager.getDocument(updateAlert.getObjectID());
    String docName = dmsDocument.getDocumentName();
    return docName;
  }

  /**
   * @param updateAlertTypeID
   * @throws ApplicationException
   * @throws SchedulerException
   */
  public void cancelInvitation(Integer updateAlertTypeID) throws ApplicationException,
      SchedulerException {
    UpdateAlertTypeDAObject updateAlertTypeDAObject = new UpdateAlertTypeDAObject(sessionContainer,
        dbConn);
    updateAlertTypeDAObject.updateInvitationCancelStatusByID(updateAlertTypeID);
    deleteExpiredJob(updateAlertTypeID);
    notificationInviteeInviteChange(updateAlertTypeID.toString(),
        UpdateAlert.DOCUMENT_INVITATION_CANCEL);
  }

  /**
   * @param updateAlertTypeID
   * @throws SchedulerException
   */
  private void deleteExpiredJob(Integer updateAlertTypeID) throws SchedulerException {
    logger.info("delete job name"+GlobalConstant.DOCUMENT_INVITATION_JOB_NAME + String.valueOf(updateAlertTypeID));
    Scheduler sched = null;
    sched = SchedulerFactory.getScheduler();
    sched.unscheduleJob(GlobalConstant.DOCUMENT_INVITATION_JOB_NAME + String.valueOf(updateAlertTypeID),
        GlobalConstant.DOCUMENT_INVITATION_JOB_GROUP);
  }

  /**
   * @param documentID
   * @param sortField
   * @param currentPage
   * @throws ApplicationException
   */
  public  List getAllInvitationList(String documentID,int currentPage, String sortAttribute,
      String sortOrder) throws ApplicationException {
    return getAllInvitationList(documentID, sessionContainer.getUserRecordID(),
        currentPage, sortAttribute, sortOrder);
  }

  /**
   * @param documentID
   * @param userID
   * @param sortField
   * @param nextLine
   * @return
   * @throws ApplicationException
   */
  public  List getAllInvitationList(String documentID, Integer userID,
       int nextLine, String sortAttribute, String sortOrder)
      throws ApplicationException {
    List allInvitationList = new ArrayList();

    AlertManager alertManager = new AlertManager(sessionContainer, dbConn);
    UpdateAlertTypeDAObject updateTypeDAO = new UpdateAlertTypeDAObject(sessionContainer, dbConn);

    UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer, dbConn);
    
    UpdateAlert updateAlert = (UpdateAlert) updateAlertDAO.getByUserID(UpdateAlert.DOCUMENT_TYPE,
        userID, TextUtility.parseIntegerObj(documentID));
    if(Utility.isEmpty(updateAlert)){
      return allInvitationList;
    }
    
    if (Utility.isEmpty(sortAttribute) || sortAttribute.trim().equalsIgnoreCase("TEADNUMBER")) {
      sortAttribute = "CREATE_DATE";
    }
    if (Utility.isEmpty(sortOrder) || sortOrder.trim().equalsIgnoreCase("asc")) {
      sortOrder = "ASC";
    }
    else {
      sortOrder = "DESC";
    }
    logger.info("sort "+sortAttribute+" "+sortOrder);
    List invitationList = updateTypeDAO.getDocumentInvitationByUpdateAlertID(updateAlert.getID(),
        UpdateAlert.INVITE_ACTION, sortAttribute, sortOrder);

    for (int i = 0; i < invitationList.size(); i++) {
      UpdateAlertType updateAlertType = (UpdateAlertType) invitationList.get(i);
      DocumentInvitationBean invitationBean = handleDocumentInvitationBean(documentID, alertManager, updateTypeDAO,
          updateAlert.getID(), updateAlertType);
      invitationBean.setRecordCount(String.valueOf(invitationList.size()));
      allInvitationList.add(invitationBean);
    }
    if (!Utility.isEmpty(sortAttribute) && sortAttribute.trim().equalsIgnoreCase("TEADNUMBER")) {
      sort(sortOrder, allInvitationList);
    }

    return pageNavigation(allInvitationList,nextLine);
  }
/**
 * 
 * @param allInvitationList
 * @param nextLine
 * @return
 */
  private List pageNavigation(List allInvitationList,int nextLine) {
    if(nextLine<1){
      nextLine=1;
    }
//  TextUtility.parseInteger(SystemParameterFactory.getSystemParameter(SystemParameterConstant.PAGE_OFF_SET));
    int pageOffset = DOCUMENT_INVITATION_PAGE_OFFSET;
    List currentPageList = new ArrayList();
    
    for(int i=(nextLine-1);i<allInvitationList.size()&&i<nextLine+pageOffset-1;i++){
      currentPageList.add(allInvitationList.get(i));
    }

    this.release();
    return currentPageList;
  }

  /**
   * @param sortOrder
   * @param allInvitationList
   */
  private void sort(final String sortOrder, List allInvitationList) {
    Collections.sort(allInvitationList, new Comparator() {
      public int compare(Object obj1, Object obj2) {
        DocumentInvitationBean bean1 = (DocumentInvitationBean) obj1;
        DocumentInvitationBean bean2 = (DocumentInvitationBean) obj2;
        Double readPercent1 = (bean1.getReadUser().size() + bean1.getUnReadUser().size()) == 0 ? new Double(
            0)
            : new Double(bean1.getReadUser().size() / bean1.getUnReadUser().size());
        Double readPercent2 = (bean2.getReadUser().size() + bean2.getUnReadUser().size()) == 0 ? new Double(
            0)
            : new Double(bean2.getReadUser().size() / bean2.getUnReadUser().size());
        int flag = 0;
        flag = readPercent1.compareTo(readPercent2);
        if (sortOrder.equalsIgnoreCase("DESC")) {
          flag *= -1;
        }
        return flag;
      }
    });
  }

  /**
   * @param documentID
   * @param alertManager
   * @param updateTypeDAO
   * @param updateAlert
   * @param invitationList
   * @param i
   * @return
   * @throws ApplicationException
   */
  private DocumentInvitationBean handleDocumentInvitationBean(String documentID, AlertManager alertManager, 
      UpdateAlertTypeDAObject updateTypeDAO, Integer updateAlertID, UpdateAlertType updateAlertType) 
  throws ApplicationException {
    
    MtmUpdateAlertRecipientDAObject mtmUpdateAlertRecipientDAObject = new MtmUpdateAlertRecipientDAObject(
        sessionContainer, dbConn);
//    UpdateAlertSystemLogDAObject updateAlertSystemLogDAObject = new UpdateAlertSystemLogDAObject(sessionContainer, dbConn);

    UserRoleDAObject userRoleDAO = new UserRoleDAObject(sessionContainer, dbConn);
    UserRecordDAObject userRecordDAO = new UserRecordDAObject(sessionContainer, dbConn);
    UserGroupDAObject userGroupDAO = new UserGroupDAObject(sessionContainer, dbConn);
    
    
    DocumentInvitationBean invitationBean = new DocumentInvitationBean();
    invitationBean.setUpdateAlertTypeID(updateAlertType.getID().toString());
    invitationBean.setDate(updateAlertType.getCreateDate());
    if(!Utility.isEmpty(updateAlertType.getDueDate())){
      invitationBean.setDueDate(updateAlertType.getDueDate());
    }
    invitationBean.setMessage(updateAlertType.getMessage());
    invitationBean.setSubject(updateAlertType.getAlertSubject());
    invitationBean.setStatus(getDocumentInvitationStatus(updateAlertType));

  
    List userIDList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(updateAlertID,
        updateAlertType.getID(), UpdateAlert.USER_RECIPIENT, GlobalConstant.RECORD_STATUS_ACTIVE);
    List groupIDList = mtmUpdateAlertRecipientDAObject
        .getRecipientIDList(updateAlertID, updateAlertType.getID(),
            UpdateAlert.GROUP_RECIPIENT, GlobalConstant.RECORD_STATUS_ACTIVE);
    List roleIDList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(updateAlertID,
        updateAlertType.getID(), UpdateAlert.ROLE_RECIPIENT, GlobalConstant.RECORD_STATUS_ACTIVE);
    List externalEmailList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(updateAlertID, updateAlertType.getID(), UpdateAlert.EXTERNAL_EMAIL,
        GlobalConstant.RECORD_STATUS_ACTIVE);

    List allInvitees = getAllInvitees(alertManager, userIDList, groupIDList, roleIDList);

    externalEmailList = alertManager.getExternalEmailByRecipientIDList(externalEmailList);

    invitationBean.setExternalEmail(externalEmailList);
    invitationBean.setRole(getInviteeRole(roleIDList, userRoleDAO));
    invitationBean.setGroup(getInviteeGroup(groupIDList, userGroupDAO));
    invitationBean.setUser(getInviteeUser(userIDList, userRecordDAO));
//    invitationBean.setReadUser(getReadDocumentUser(updateAlertID, TextUtility
//        .parseIntegerObj(documentID),updateTypeDAO,updateAlertSystemLogDAObject));
    InvitationFacade invitationFacade = new InvitationDocumentView(sessionContainer,dbConn);
    try{
     invitationBean.setReadUser(invitationFacade.getReadDocmentUser(documentID,updateAlertType,allInvitees));
    }catch(Exception e){
      logger.error(e, e);
    } 
    //invitationBean.setReadUser(getReadMessageUser(updateAlertType,allInvitees));
    allInvitees.removeAll(invitationBean.getReadUser());
    invitationBean.setUnReadUser(allInvitees);
    return invitationBean;
  }
  /**
   * 
   * @param date
   * @return
   */
/*  
    private String parseDate(Date date) {
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",sessionContainer.getSessionLocale());
      return formatter.format(date);
    }
*/
  
/**
 * 
 * @param updateAlertID
 * @param documentID
 * @param updateTypeDAO
 * @param updateAlertSystemLogDAObject
 * @return
 * @throws ApplicationException
 */
  private List getReadDocumentUser(Integer updateAlertID, Integer documentID, 
                  UpdateAlertTypeDAObject updateTypeDAO, UpdateAlertSystemLogDAObject updateAlertSystemLogDAObject) throws ApplicationException {
    List readUserNameList = new ArrayList();
    UpdateAlertType updateAlertType =updateTypeDAO.getByUpdateAlertIDAndActionType(updateAlertID, 
                                                                  UpdateAlert.VIEW_ACTION);
    readUserNameList = updateAlertSystemLogDAObject.getCreatUserNameListByUpdateAlertTypeID(updateAlertType.getID());
    
    return readUserNameList;
  }
  /**
   * 
   * @param allInvitees 
   * @param updateAlertID
   * @param documentID
   * @param updateTypeDAO
   * @param updateAlertSystemLogDAObject
   * @return
   * @throws ApplicationException
   */
    private List getReadMessageUser(UpdateAlertType updateAlertType, List allInvitees) throws ApplicationException {
      List readUserNameList = new ArrayList();
      if(Utility.isEmpty(allInvitees)){
        return readUserNameList;
      }

      UpdateAlertTypeDAObject updateTypeDAO = new UpdateAlertTypeDAObject(sessionContainer, dbConn);
      List updateTypeList = updateTypeDAO.getDocumentInvitationByUpdateAlertID(updateAlertType.getUpdateAlertID(),
          UpdateAlert.INVITE_ACTION,"CREATE_DATE","DESC");
      List tempList = new ArrayList();
      UpdateAlertType tempAlertType;
      //get all  after the updateAlerttype create time 
      for(int i=0;i<updateTypeList.size();i++){
        tempAlertType = (UpdateAlertType)updateTypeList.get(i);
        if(tempAlertType.getCreateDate().before(updateAlertType.getCreateDate())){
          break;
        }
        tempList.add(tempAlertType);
      }
      
      for(int j=0;j<tempList.size();j++){
        tempAlertType = (UpdateAlertType)tempList.get(j);
        List userName = getReadMessageUser(tempAlertType);
        for(int l=0;l<userName.size();l++){
          if(allInvitees.contains(userName.get(l))&&!readUserNameList.contains(userName.get(l))){
            readUserNameList.add(userName.get(l));
          }
        }
      }
      return readUserNameList;
    }

  /**
   * @param updateAlertType
   * @param readUserNameList
   * @throws ApplicationException
   */
  private List getReadMessageUser(UpdateAlertType updateAlertType) throws ApplicationException {
    List readUserNameList = new ArrayList();
    UpdateAlertLogActionDAObject logActionDAO = new UpdateAlertLogActionDAObject(sessionContainer, dbConn); 

   List logList = logActionDAO.getListByUpdateAlertTypeID(updateAlertType.getID());
    for(int i=0;i<logList.size();i++){
      UpdateAlertLogAction updateAlertLogAction = (UpdateAlertLogAction)logList.get(i);
      readUserNameList.add(UserInfoFactory.getUserFullName(updateAlertLogAction.getActorID()));        
    }
    return readUserNameList;
  }
/**
 * 
 * @param userIDList
 * @param userRecordDAO
 * @return
 * @throws ApplicationException
 */
  private List getInviteeUser(List userIDList, UserRecordDAObject userRecordDAO)
      throws ApplicationException {
    List userList = new ArrayList();
    for (int i = 0; i < userIDList.size(); i++) {
      Integer userID = (Integer) userIDList.get(i);
      UserRecord user = (UserRecord) userRecordDAO.getObjectByID(userID);
      userList.add(user);
    }

    return userList;
  }
/**
 * 
 * @param groupIDList
 * @param userGroupDAO
 * @return
 * @throws ApplicationException
 */
  private List getInviteeGroup(List groupIDList, UserGroupDAObject userGroupDAO)
      throws ApplicationException {
    List groupList = new ArrayList();
    for (int i = 0; i < groupIDList.size(); i++) {
      Integer groupID = (Integer) groupIDList.get(i);
      UserGroup userGroup = (UserGroup) userGroupDAO.getObjectByID(groupID);
      groupList.add(userGroup);
    }

    return groupList;
  }

  /**
   * @param roleIDList
   * @param userRoleDAO
   * @return
   * @throws ApplicationException
   */
  private List getInviteeRole(List roleIDList, UserRoleDAObject userRoleDAO)
      throws ApplicationException {
    List roleList = new ArrayList();
    for (int i = 0; i < roleIDList.size(); i++) {
      Integer roleID = (Integer) roleIDList.get(i);
      UserRole userRole = (UserRole) userRoleDAO.getObjectByID(roleID);
      roleList.add(userRole);
    }

    return roleList;
  }

  /**
   * @param alertManager
   * @param userList
   * @param groupList
   * @param roleList
   * @return
   * @throws ApplicationException
   */
  private List getAllInvitees(AlertManager alertManager, List userList, List groupList,
      List roleList) throws ApplicationException {
    List allInvitees = new ArrayList();
    String[] allUserList = new String[userList.size()];
    String[] allGroupList = new String[groupList.size()];
    String[] allRoleList =  new String[roleList.size()];

    for(int i =0;i<userList.size();i++){
      if(!Utility.isEmpty(userList.get(i))){
      allUserList[i]=userList.get(i).toString();
    }
    }
    for(int j =0;j<groupList.size();j++){
      if(!Utility.isEmpty(groupList.get(j))){
      allGroupList[j]=groupList.get(j).toString();
    }
    }
    for(int l =0;l<roleList.size();l++){
      if(!Utility.isEmpty(roleList.get(l))){
      allRoleList[l]=roleList.get(l).toString();
    }
    }
    
    List notifyUserIDList = alertManager.getDistinctUserIDListByLists(allUserList, allGroupList,
        allRoleList);
    for (int i = 0; i < notifyUserIDList.size(); i++) {
      Integer userID = (Integer) notifyUserIDList.get(i);
      String userName = UserInfoFactory.getUserFullName(userID);
      allInvitees.add(userName);
    }
    return allInvitees;
  }
/**
 * 
 * @param updateType
 * @return
 */
  public String getDocumentInvitationStatus(UpdateAlertType updateType) {
    String status = "";
    if (!Utility.isEmpty(updateType.getStatus())
        && updateType.getStatus().trim().equalsIgnoreCase(UpdateAlert.STATUS_CANCEL)) {
      status = UpdateAlert.STATUS_CANCEL;
    }
    else if (!Utility.isEmpty(updateType.getDueDate())
        && Utility.addDay(updateType.getDueDate(),1).before(new Date())) {
      status = DocumentInvitationManager.STATUS_EXPIRED;
    }
    else {
      status = DocumentInvitationManager.STATUS_ACTIVE;
    }
    return status;
  }

  /**
   * @param updateAlertTypeyID
   * @throws ApplicationException 
   */
  public Object getInvitationByUpdateAlertID(String updateAlertTypeyID) throws ApplicationException {

    Integer updateTypeID = TextUtility.parseIntegerObj(updateAlertTypeyID);

    AlertManager alertManager = new AlertManager(sessionContainer, dbConn);
    UpdateAlertTypeDAObject updateTypeDAO = new UpdateAlertTypeDAObject(sessionContainer, dbConn);

    UpdateAlertType updateAlertType = (UpdateAlertType) updateTypeDAO.getObjectByID(updateTypeID);

    MtmUpdateAlertRecipientDAObject mtmUpdateAlertRecipientDAObject = new MtmUpdateAlertRecipientDAObject(
        sessionContainer, dbConn);

    UserRoleDAObject userRoleDAO = new UserRoleDAObject(sessionContainer, dbConn);
    UserRecordDAObject userRecordDAO = new UserRecordDAObject(sessionContainer, dbConn);
    UserGroupDAObject userGroupDAO = new UserGroupDAObject(sessionContainer, dbConn);

    DocumentInvitationBean invitationBean = new DocumentInvitationBean();
    invitationBean.setUpdateAlertTypeID(updateAlertType.getID().toString());
    invitationBean.setDate(updateAlertType.getCreateDate());
    if(!Utility.isEmpty(updateAlertType.getDueDate())){
    invitationBean.setDueDate(updateAlertType.getDueDate());
    }
    invitationBean.setMessage(updateAlertType.getMessage());
    invitationBean.setSubject(updateAlertType.getAlertSubject());
    invitationBean.setStatus(getDocumentInvitationStatus(updateAlertType));

    Integer updateAlertID = updateAlertType.getUpdateAlertID();
    List userIDList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(updateAlertID,
        updateAlertType.getID(), UpdateAlert.USER_RECIPIENT, GlobalConstant.RECORD_STATUS_ACTIVE);
    List groupIDList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(updateAlertID,
        updateAlertType.getID(), UpdateAlert.GROUP_RECIPIENT, GlobalConstant.RECORD_STATUS_ACTIVE);
    List roleIDList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(updateAlertID,
        updateAlertType.getID(), UpdateAlert.ROLE_RECIPIENT, GlobalConstant.RECORD_STATUS_ACTIVE);
    List externalEmailList = mtmUpdateAlertRecipientDAObject.getRecipientIDList(updateAlertID,
        updateAlertType.getID(), UpdateAlert.EXTERNAL_EMAIL, GlobalConstant.RECORD_STATUS_ACTIVE);

    List allInvitees = getAllInvitees(alertManager, userIDList, groupIDList, roleIDList);

    externalEmailList = alertManager.getExternalEmailByRecipientIDList(externalEmailList);

    invitationBean.setExternalEmail(externalEmailList);
    invitationBean.setRole(getInviteeRole(roleIDList, userRoleDAO));
    invitationBean.setGroup(getInviteeGroup(groupIDList, userGroupDAO));
    invitationBean.setUser(getInviteeUser(userIDList, userRecordDAO));
    //    invitationBean.setReadUser(getReadDocumentUser(updateAlertID, TextUtility
    //          .parseIntegerObj(documentID),updateTypeDAO,updateAlertSystemLogDAObject));
    invitationBean.setReadUser(getReadMessageUser(updateAlertType,allInvitees));
    allInvitees.removeAll(invitationBean.getReadUser());
    invitationBean.setUnReadUser(allInvitees);
    invitationBean.setRecordCount("1");
    return invitationBean;

  }

}
